package com.lechuang.gateway.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.lechuang.common.constant.BaseConstant;
import com.lechuang.gateway.constant.Constant;
import com.lechuang.gateway.util.IPUtils;
import lombok.extern.log4j.Log4j2;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * <p>
 *  请求日志记录拦截器
 * </p>
 *
 * @author liaoningbo
 * @since 2024-01-08
 */
@Component
@Log4j2
public class LogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("日志拦截开始");
        try{
            ServerHttpRequest request = exchange.getRequest();
            long startTime = System.currentTimeMillis();
            //设置唯一请求id
            String traceId = IdUtil.fastUUID();
            MDC.put(BaseConstant.TRACE_ID, traceId);
            exchange.getRequest().mutate().headers(httpHeaders -> httpHeaders.add(BaseConstant.TRACE_ID, traceId));
            //打印请求参数
            log.info("\n" + "url: " + request.getURI().toASCIIString() + "\n" +
                    "ip: " + IPUtils.getIpAddress(request) + "\n" +
                    "path: " + request.getPath() + "\n" +
                    "method: " + request.getMethod() + "\n" +
                    "header: " + JSONUtil.toJsonStr(request.getHeaders().toSingleValueMap()) + "\n" +
                    "param: " + JSONUtil.toJsonStr(request.getQueryParams()));
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("traceId为{}的请求完成，url: {}, 耗时:{}ms", traceId, request.getURI().toASCIIString(), System.currentTimeMillis() - startTime);
            }));
        }finally {
            MDC.clear();
            log.info("日志拦截结束");
        }

    }

    @Override
    public int getOrder() {
        return Constant.LOG_FILTER_ORDER;
    }
}
